package com.gopay.bis.web.controller.ebank;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.pab.ebank.PabOrderMessageRes;
@Controller
@Scope("prototype")
public class PabB2bFrontRes  extends BankResBase {
	
	private static Log logger = LogFactory.getLog(PabB2bServerRes.class);

	@RequestMapping(value = "/pabB2bFrontRes")
	protected ModelAndView execute(HttpServletRequest request,HttpServletResponse response) {
		logger.error("--------------- PabB2bFrontRes bankback ---------------");
		return super.execute(request, response);
	}

	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		PabOrderMessageRes message = new PabOrderMessageRes();
		String plainMessage = request.getParameter("orig");// 平安银行回应订单信息
		String signMessage = request.getParameter("sign");// 平安银行回应签名
		if (StringUtils.isEmpty(plainMessage) || StringUtils.isEmpty(signMessage)) {
			logger.error("平安银行B2B支付通知明文或密文为空，通知网关。");
		}
		if (StringUtils.isNotBlank(plainMessage)) {
			try {
				plainMessage = new String(plainMessage.getBytes("ISO8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		message.setBank(BankConstants.BANK_LOGO_PAB);
		message.setFront(true);
		message.setPlainMessage(plainMessage);
		message.setSignMessage(signMessage);
		// 银行业务产品01企业网银支付
		message.setBankBusProd(BisBankBusinessProd._01);
		if (StringUtils.isNotBlank(plainMessage)) {
			Map map = getOrigData(plainMessage);
			message.setCommitFlag((String) map.get("status"));
			message.setBankOrderId((String) map.get("orderid"));
			message.setAmount(new BigDecimal((String) map.get("amount")));
		}
		return message;
	
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		OrderInfo orderInfo = new OrderInfo();
		if (result.getModel("res") != null) {
			PabOrderMessageRes message = (PabOrderMessageRes) result.getModel("res");
			orderInfo.setOrderId(message.getOrderId());
			orderInfo.setAmt(message.getAmount().toString());
		} else {
			String plainMessage = request.getParameter("orig");// 平安银行回应订单信息
			if (StringUtils.isNotBlank(plainMessage)) {
				Map map = getOrigData(plainMessage);
				orderInfo.setOrderId((String) map.get("orderid"));
				orderInfo.setAmt((String) map.get("amount"));
			}
		}
		orderInfo.setNotifyNum("1");
		orderInfo.setPayStatus("");
		orderInfo.setRetCode("00");
		orderInfo.setRetMsg("");
		return orderInfo;
	}

	/**
	 * 获取深发展银行回应的orig信息
	 * 
	 * @param orig
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map getOrigData(String orig) {
		if (orig == null || orig.trim().length() == 0) {
			logger.error("平安银行回应订单信息有误：不能为空");
			return new HashMap();
		}
		Map map = new HashMap();
		String[] datas = orig.trim().split("\\|");
		for (int i = 0; i < datas.length; i++) {
			String data = datas[i].trim();
			int index = data.indexOf("=");
			String key = data.substring(0, index).trim();
			String value = data.substring(index + 1).trim();
			map.put(key, value);
		}
		return map;
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		if (StringUtils.isEmpty(request.getParameter("orig"))|| StringUtils.isEmpty(request.getParameter("sign"))) {
			return false;
		}
		return true;
	}
}
